<!--
 * @Author: zhangjingyu
 * @Date: 2020-11-04 19:43:11
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-05-07 09:02:10
 * @Description: 口径层级页面
-->
<template>
  <!-- 口径层级页面 -->
  <div>
    <el-row class="caliberHierarchy container" :gutter="20">
      <el-col :span="18" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.page=1,searchFunc()"
          @clear="
            (searchForm.treeTypeCode = ''),
              (searchForm.treeTypeName = ''),
              (searchForm.caliberProjectCode = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addFunc">新增</el-button>
            <el-button @click="editFunc">编辑</el-button>
            <el-button @click="deleteFunc">删除</el-button>
            <el-button @click="viewFunc">查看</el-button>
            <el-button @click="configFun">配置层级</el-button>
            <el-button @click="setAsDefault">设为默认</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="100px"
              label-position="right"
              size="mini"
            >
              <el-form-item label="树编码：">
                <el-input
                  v-model="searchForm.treeTypeCode"
                  placeholder="请输入树编码"
                ></el-input>
              </el-form-item>
              <el-form-item label="树名称：" prop="treeTypeName">
                <el-input
                  v-model="searchForm.treeTypeName"
                  placeholder="请输入树名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="口径方案：" prop="caliberProjectCode">
                <el-select
                  v-model="searchForm.caliberProjectCode"
                  placeholder="请选择口径方案"
                  style="width:100%"
                >
                  <el-option
                    v-for="item in caliberProjectList"
                    :label="item.caliberProjectName"
                    :value="item.caliberProjectCode"
                    :key="item.caliberProjectCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :disabled="item.checkDisabled"
                :key="item.prop"
                >{{ item.label }}</el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>

        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="tableRowClick"
          id="kind-option"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            v-for="(item, key) in showData"
            :key="key"
            :prop="item.prop"
            :label="item.label"
            :show-overflow-tooltip="true"
            :render-header="item.render"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :width="item.width"
            :min-width="item.minwidth"
          ></el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
      <el-col :span="6" class="content-right">
        <div class="title">
          <div style="float:left"><span class="gun"></span> {{ treeName }}</div>
        </div>
        <vp-tree
        vp-title="层级"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          ref="caliberTree"
          node-key="dictItemCode"
          :render-content="renderTree"
        >
        </vp-tree>
      </el-col>
    </el-row>
    <!-- 新增编辑查看弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
      top="2%"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="120px"
        label-position="left"
        :rules="saveFormRules"
        :disabled="saveFlg == 3"
      >
        <el-form-item
          label="层级树编码："
          v-if="saveFlg != 1"
          prop="treeTypeCode"
        >
          <el-input v-model="saveForm.treeTypeCode" disabled maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="层级树名称：" prop="treeTypeName">
          <el-input v-model="saveForm.treeTypeName" maxlength="64" placeholder="请输入层级树名称"></el-input>
        </el-form-item>
        <el-form-item label="口径方案：" prop="caliberProjectCode">
          <el-select
            v-model="saveForm.caliberProjectCode"
            placeholder="请选择口径方案"
            style="width:100%"
          >
            <el-option
              v-for="item in caliberProjectList"
              :label="item.caliberProjectName"
              :value="item.caliberProjectCode"
              :key="item.caliberProjectCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述：" prop="descn">
          <el-input v-model="saveForm.descn" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc" v-if="saveFlg != 3">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 配置层级弹窗 -->
    <el-dialog
      v-dialogDrag
      title="口径层级配置"
      :visible.sync="isConfigDialog"
      width="70%"
      top="2%"
    >
      <el-row  :gutter="10">
        <el-col :span="14">
          <upper-template
            @search="searchFF.page=1,searchFFunc()"
            :configIcon="false"
            @clear="(searchFF.caliberName = ''), (searchFF.caliberCode = '')"
          >
            <div slot="buttonArea"></div>
            <div slot="searchArea">
              <el-form
                :model="searchFF"
                ref="searchFF"
                label-width="87px"
                label-position="left"
                size="mini"
              >
                <el-form-item label="口径编码：" prop="caliberCode">
                  <el-input
                    v-model="searchFF.caliberCode"
                    placeholder="请输入口径编码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="口径名称：" prop="caliberName">
                  <el-input v-model="searchFF.caliberName"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </upper-template>

          <el-table
            ref="configTable"
            :data="configTableData"
            @row-click="getConfigTree"
          >
            <el-table-column
              width="55"
              type="selection"
              
            ></el-table-column>
            <el-table-column
              v-for="(item, key) in showConfigData"
              :key="key"
              :prop="item.prop"
              :label="item.label"
              :align="item.align"
              :width="item.width"
              :show-overflow-tooltip="true"
              :render-header="item.render"
              :sortable="item.sortable"
              :formatter="item.formatter"
            ></el-table-column>
          </el-table>

          <pagination
            @size-change="handleSizeChangeConf"
            @current-change="handleCurrentChangeConf"
            :current-page="searchFF.page"
            @refresh="searchFFunc"
            :pager-count="5"
            :page-size="searchFF.size"
            :total="totalConf"
          ></pagination>
        </el-col>
        <el-col :span="10" >
          <upper-template noIcon >
            <div slot="buttonArea">
               <el-button @click="addNextTree">+下级树集</el-button>
            <el-button @click="addNextNode">+下级叶子</el-button>
            <el-button @click="delNode">删除</el-button>
            </div>
          </upper-template>
      
          <vp-tree
            vp-title="层级"
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            @check="handleNodeClick"
            default-expand-all
            show-checkbox
            ref="caliberConfigTree"
            node-key="dictItemCode"
            check-strictly
            check-on-click-node
            :expand-on-click-node="false"
            :render-content="renderTree"
          ></vp-tree>
        </el-col>
      </el-row>

      <el-dialog
        v-dialogDrag
        width="514px"
        title="添加口径集"
        :visible.sync="isAddNextTree"
        append-to-body
      >
        <el-form
          :model="addTreeForm"
          ref="addTreeForm"
          :rules="addTreeFormRules"
          label-position="left"
        >
          <el-form-item label="口径编码：" label-width="100px" prop="caliberCode">
            <el-input
              v-model="addTreeForm.caliberCode"
              autocomplete="off"
              placeholder="请输入口径编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="口径名称：" label-width="100px" prop="caliberName">
            <el-input
              v-model="addTreeForm.caliberName"
              autocomplete="off"
              maxlength="40"
              placeholder="请输入口径名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="saveBroNodeParent">确 定</el-button>
          <el-button @click="isAddNextTree = false">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer"></div>
    </el-dialog>
  </div>
</template>

<script>
// import iscroll from 'iscroll'
import { publicManage_pub } from "@/api/index";
export default {
  data() {
    return {
      treeName: "",
      addOrEdit: false, // 新增/编辑/查看弹窗
      isConfigDialog: false, // 配置层级弹窗
      serachMore: false, // 配置层级搜索是否收起
      isAddNextTree: false, // 添加下级树集弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: [
        "添加口径层级树基本信息数据表信息",
        "修改口径层级树基本信息数据表信息",
        "查看口径层级"
      ],
      // 口径方案list
      caliberProjectList: [],
      searchForm: {
        treeTypeCode:"",
        treeTypeName:"",
        caliberProjectCode:"",
        page: 1,
        size: 15
      },
      saveForm: {
        treeTypeId: "",
        treeTypeCode: "",
        treeTypeName: "",
        caliberProjectCode: "",
        descn: ""
      },
      saveFormRules: {
        treeTypeCode: [
          { required: true, message: "请输入层级树编码", trigger: "blur" },
        ],
        treeTypeName: [
          { required: true, message: "请输入层级树名称", trigger: "blur" },
          { min: 1, max: 50, message: "内容介于 1 到 50 个字符之间", trigger: "blur" }
        ],
        caliberProjectCode: [
          { required: true, message: "请选择口径方案", trigger: "blur" }
        ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        {
          prop: "treeTypeCode",
          label: "树编码",
          align: "center",
          checkDisabled: true
        },
        {
          prop: "treeTypeName",
          label: "树名称",
          sortable: true,
          checkDisabled: true
        },
        {
          prop: "caliberProject.caliberProjectName",
          label: "口径方案 ",
          checkDisabled: true
        },
        {
          prop: "defaultTree",
          label: "是否默认",
          align: "center",
          formatter: row => {
            return row.defaultTree == 1 ? "是" : "否";
          }
        },
        { prop: "descn", label: "口径层级描述 " }
      ],
      // 获取table的数据
      tableData: [],
      total: 1,
      totalConf: 1,
      defaultProps: {
        children: "children",
        label: "dictItemName"
      },
      treeData: [],
      searchFF: {
        caliberCode: "",
        caliberName: "",
        page: 1,
        size: 15
      },
      // 口径层级配置表格列配置
      showConfigData: [
        { prop: "caliberCode", label: "口径编码", align: "right", width: 120 },
        { prop: "caliberName", label: "口径名称" },
        { prop: "caliberProject.caliberProjectName", label: "所属口径方案 " }
      ],
      configTableData: [],
      addTreeForm: {
        caliberName: "",
        caliberCode: ""
      },
      addTreeFormRules: {
         caliberCode: [
           { required: true, message: "请输入口径编码", trigger: "blur" },
           {
            pattern: /^[0-9a-zA-Z_]{1,30}$/,
            message: "只能输入1-30位的英文字母、数字、下划线",
            trigger: "blur"
          },
         ],
         caliberName: [
           { required: true, message: "请输入口径名称", trigger: "blur" },

         ]
        
      }
    };
  },
  created() {
    this.checkListInit();
  },
  computed: {
    // 展示字段
    showData() {
      let arr = this.textData.map(v => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach(element => {
        let flag = false;
        this.checkList.forEach(e => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    }
  },
  mounted() {
    this.getList();
    this.searchFunc();
  },
  watch: {
       addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    }
  },
  methods: {
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    searchFunc() {
      console.log(this.searchForm, "搜索");
      publicManage_pub.caliberHierarchyQuery(this.searchForm).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.sort((x,y)=>(y.defaultTree-x.defaultTree));
          this.total = res.count;
        }
      });
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = {
        treeTypeId: row.treeTypeId,
        treeTypeCode: row.treeTypeCode,
        treeTypeName: row.treeTypeName,
        caliberProjectCode: row.caliberProject.caliberProjectCode,
        descn: row.descn
      };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    // 保存
    saveFunc() {
      console.log(this.saveForm);
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm
          };
          publicManage_pub.caliberHierarchySave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.addOrEdit = false;
              this.searchFunc();
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    deleteFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            caliberProjectCodes: selection.map(
              v => v.caliberProject.caliberProjectCode
            ),
            treeTypeCodes: selection.map(v => v.treeTypeCode)
          };
          publicManage_pub.caliberHierarchyDel(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    viewFunc() {
      this.saveFlg = 3;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }

      let row = selection[0];
      let form = {
        treeTypeId: row.treeTypeId,
        treeTypeCode: row.treeTypeCode,
        treeTypeName: row.treeTypeName,
        caliberProjectCode: row.caliberProject.caliberProjectCode,
        descn: row.descn
      };
      this.saveForm = form;
      this.addOrEdit = true;
    },
    setAsDefault() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行设置");
      }

      this.$confirm("您确认要将此条设为默认吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            caliberProjectCode: selection[0].caliberProject.caliberProjectCode,
            treeTypeId: selection[0].treeTypeId
          };
          publicManage_pub.caliberHierarchySetDefault(data).then(res => {
            if (res.code == 200) {
              this.$message.success("设为默认成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "设为默认失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    handleNodeClick(obj) {
      console.log(obj);
      this.$refs.caliberConfigTree.$tree.setCheckedNodes([]);
      this.$refs.caliberConfigTree.$tree.setCheckedNodes([obj]);
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    getList() {
      publicManage_pub.caliberHierarchyFindCaliberProjectList().then(res => {
        if (res.code == 200) {
          this.caliberProjectList = res.data;
        }
      });
    },
    // 点击表格某行
    tableRowClick(row) {
      this.treeName = row.treeTypeName;
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
      this.treeSearchRow = row;
      this.getTree();
    },
    // 获取口径树
    getTree() {
      let data = {
        caliberProjectCode: this.treeSearchRow.caliberProject
          .caliberProjectCode,
        treeTypeCode: this.treeSearchRow.treeTypeCode
      };
      publicManage_pub.caliberHierarchyCaliberTreeNodeTree(data).then(res => {
        // console.log(res.data);
        this.treeData = this.$listToTree(
          "dictItemCode",
          "parentItemCode",
          res.data
        );
      });
    },
    // 获取层级配置口径树
    getConfigTree(row) {
      this.$refs.configTable.toggleRowSelection(row);
    },
    configFun() {
      let checked = this.$refs.multipleTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.isConfigDialog = true;
        this.treeSearchRow = checked[0];
        this.getTree();
        this.searchFFunc();
      }
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
      console.log(`当前页: ${val}`);
    },
    handleSizeChangeConf(val) {
      this.searchFF.size = val;
      this.searchFFunc();
    },
    handleCurrentChangeConf(val) {
      this.searchFF.page = val;
      this.searchFFunc();
    },
    // 口径层级配置弹窗左表查询
    searchFFunc() {
      console.log("查询");
      let data = {
        caliberProjectCode: this.treeSearchRow.caliberProject
          .caliberProjectCode,
        treeTypeCode: this.treeSearchRow.treeTypeCode,
        ...this.searchFF
      };
      publicManage_pub.caliberHierarchyQueryGridForTree(data).then(res => {
        if (res.code == 200) {
          this.configTableData = res.data;
          this.totalConf = res.count;
        }
      });
    },
    // 增加下级树集
    addNextTree() {
      let node = this.$refs.caliberConfigTree.$tree.getCheckedNodes();
      console.log(node);
      if (node.length === 0) {
        return this.$message.warning("请为添加的口径集选择上级口径集");
      }
      if (node[0].parentItemCode) {
        return this.$message.warning("选择的上级非口径集，请重新选择上级口径集");
      }
      // let data = { parentNodeItemCode: node[0].dictItemCode };
      // publicManage_pub
      //   .caliberHierarchyCheckCaliberTreeNodeLevel(data)
      //   .then(res => {
      //     console.log(res);
      //   });
      this.isAddNextTree = true;
      for (const key in this.addTreeForm) {
        this.addTreeForm[key] = "";
      }
    },
    // 保存下级树集
    saveBroNodeParent() {
      this.$refs["addTreeForm"].validate(valid => {
        if (valid) {
          let node = this.$refs.caliberConfigTree.$tree.getCheckedNodes()[0];

          let data = {
            ...this.addTreeForm,
            parentNodeItemCode: node.dictItemCode,
            caliberProjectCode: this.treeSearchRow.caliberProject
              .caliberProjectCode,
            treeTypeCode: this.treeSearchRow.treeTypeCode,
            treeTypeId: this.treeSearchRow.treeTypeId
          };
          publicManage_pub.caliberHierarchyCheckDefCodesu(data).then(res => {
            if (res.success && res.code == 200) {
              publicManage_pub
                .caliberHierarchyAddBroNodeParent(data)
                .then(res => {
                  if (res.code == 200) {
                    this.$message.success("保存成功");
                    this.isAddNextTree = false;
                    this.getTree();
                  } else {
                    this.$message.error(res.message || "保存失败");
                  }
                });
            } else {
              this.$message.error(res.message || "校验不通过，请检查输入格式");
            }
          });
        }
      });
    },
    // 增加下级子叶
    addNextNode() {
      let nodes = this.$refs.caliberConfigTree.$tree.getCheckedNodes();
      if (nodes.length === 0) {
        return this.$message.warning("请选择一个节点");
      }
      let selection = this.$refs.configTable.selection;
      if (selection.length === 0) {
        return this.$message.warning("请选择左侧口径作为添加的节点");
      }
      let data = {
        caliberCodes: selection.map(v => v.caliberCode),
        parentNodeItemCode: nodes[0].dictItemCode,
        caliberProjectCode: this.treeSearchRow.caliberProject
          .caliberProjectCode,
        treeTypeCode: this.treeSearchRow.treeTypeCode,
        treeTypeId: this.treeSearchRow.treeTypeId
      };
      publicManage_pub.caliberHierarchyAddNode(data).then(res => {
        if (res.code == 200) {
          this.$message.success("添加节点成功");
          this.getTree();
          this.searchFFunc();
        } else {
          this.$message.error(res.message || "添加节点失败");
        }
      });
      console.log(nodes, selection);
    },
    // 删除节点
    delNode() {
      let nodes = this.$refs.caliberConfigTree.$tree.getCheckedNodes();
      console.log(nodes);
      if (nodes.length < 1) {
        return this.$message.warning("请选择要删除的节点");
      }
      this.$confirm("您确认要删除节点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            caliberProjectCode: this.treeSearchRow.caliberProject
              .caliberProjectCode,
            nodeItemCode: nodes[0].dictItemCode,
            seq: nodes[0].seq,
            treeTypeCode: this.treeSearchRow.treeTypeCode
          };
          publicManage_pub
            .caliberHierarchyTreeNodeRemoveNode(data)
            .then(res => {
              if (res.code == 200) {
                this.$message.success("删除节点成功");
                this.getTree();
                this.searchFFunc();
              } else {
                this.$message.error(res.message || "删除节点失败");
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    renderTree(h, { node, data, store }) {
      return <span>{data.dictItemCode + "-" + data.dictItemName}</span>;
    }
  }
};
</script>

<style lang="scss" scoped>
</style>